﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace GTAExtend
{
    /// <summary>
    /// Gives some static help methods, mostly for debugging
    /// </summary>
    public class G_Helper
    {
        /// <summary>
        /// if an exception occurs inside this api, your script can be informed.
        /// In this case YOU decide what to do of this exception, you can throw it or swallow it.
        /// this is used with a pattern that log script behaviors, no demo yet...
        /// </summary>
        public static  event ThreadExceptionEventHandler ThreadException;

        /// <summary>
        /// If you want to log an exception
        /// <seealso cref="ThreadException"/>
        /// </summary>
        /// <param name="err"></param>
        public static void RaiseThreadException(Exception err)
        {
            if (err == null)
                throw new ArgumentNullException("err");
            LogText("GTAExtend Internal", err.ToString());
            if (ThreadException != null)
                ThreadException(null, new ThreadExceptionEventArgs(err));
            else throw err;
        }

        /// <summary>
        /// Log the text to GTAExtend.log
        /// each log contains current datetime and the script filename path
        /// </summary>
        /// <param name="script">can't be null</param>
        /// <param name="text">text to log</param>
        public static void LogText(GTA.Script script, String text)
        {
            if (script == null)
                throw new ArgumentNullException("script");
            LogText(script.Filename, text);
        }

        /// <summary>
        /// Log text to GTAExtend.log
        /// <paramref name="sender"/> can't be null
        /// </summary>
        /// <param name="sender">source of the event, for exemple the script name. It can't be null</param>
        /// <param name="text">text to log</param>
        private static void LogText(String sender,String text)
        {
            if (text == null)
                throw new ArgumentNullException("text");
            
            using (TextWriter writer = new StreamWriter("GTAExtend.log", true, Encoding.UTF8))
            {
                writer.WriteLine("---------------------------------------");
                writer.WriteLine(String.Format("{0} ({1}) :", DateTime.Now, sender.ToString()));
                writer.WriteLine("....");
                writer.WriteLine(text);
            }
        }
    }
}
